package springboot.demo.service;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/websocket")
public class WebSocket {
	
	private static ConcurrentHashMap<String, Session>concurrentHashMap = new ConcurrentHashMap<String, Session>();
	
	@OnOpen
	public void onOpen(Session session) {
		concurrentHashMap.put(session.getQueryString(), session);
		System.out.println(session.getQueryString());
	}
	
	@OnMessage
	public void onMessage(String message, Session session) {
		System.out.println(message);
	}
	
	@OnClose
	public void onClose(Session session) {
		concurrentHashMap.remove(session.getQueryString());
		System.out.println("close: "+session.getQueryString());
	}
	
	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println(session.getQueryString());
	}
	
	public void sendMessage(String message, String id) {
		try {
			concurrentHashMap.get(id).getBasicRemote().sendObject(message);
		} catch (IOException | EncodeException e) {
			e.printStackTrace();
		}
	}
}
